/*
 * @Author: SamZhang samzhang@apjcorp.com
 * @Date: 2022-12-02 10:14:44
 * @LastEditors: SamZhang samzhang@apjcorp.com
 * @LastEditTime: 2023-02-16 15:15:51
 * @FilePath: /circulation-web/src/components/SitewideSettings.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import EditableConfigList, {
  EditableConfigListStateProps,
  EditableConfigListDispatchProps,
  EditableConfigListOwnProps,
} from "./EditableConfigList";
import { connect } from "react-redux";
import ActionCreator from "../actions";
import { SitewideSettingsData, SitewideSettingData } from "../interfaces";
import SitewideSettingEditForm from "./SitewideSettingEditForm";

const applocation_root = localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT");
/** Right panel for sitewide settings on the system configuration page.
    Shows a list of current sitewide settings and allows creating a new
    setting or editing or deleting an existing setting. */
export class SitewideSettings extends EditableConfigList<
  SitewideSettingsData,
  SitewideSettingData
> {
  EditForm = SitewideSettingEditForm;
  listDataKey = "settings";
  itemTypeName = "sitewide setting";
  urlBase = applocation_root + "/admin/web/config/sitewideSettings/";
  identifierKey = "key";
  labelKey = "key";

  label(item): string {
    for (const setting of this.props.data.all_settings) {
      if (setting.key === item.key) {
        return setting.label;
      }
    }
    return item.key;
  }
}

function mapStateToProps(state, ownProps) {
  // fetchError = an error involving loading the list of sitewide settings; formError = an error upon submission of the
  // create/edit form.
  return {
    data: state.editor.sitewideSettings && state.editor.sitewideSettings.data,
    responseBody:
      state.editor.sitewideSettings &&
      state.editor.sitewideSettings.successMessage,
    fetchError: state.editor.sitewideSettings.fetchError,
    formError: state.editor.sitewideSettings.formError,
    isFetching:
      state.editor.sitewideSettings.isFetching ||
      state.editor.sitewideSettings.isEditing,
  };
}

function mapDispatchToProps(dispatch, ownProps) {
  const actions = new ActionCreator(null, ownProps.csrfToken);
  return {
    fetchData: () => dispatch(actions.fetchSitewideSettings()),
    editItem: (data: FormData) => dispatch(actions.editSitewideSetting(data)),
    deleteItem: (identifier: string | number) =>
      dispatch(actions.deleteSitewideSetting(identifier)),
  };
}

const ConnectedSitewideSettings = connect<
  EditableConfigListStateProps<SitewideSettingsData>,
  EditableConfigListDispatchProps<SitewideSettingsData>,
  EditableConfigListOwnProps
>(
  mapStateToProps,
  mapDispatchToProps
)(SitewideSettings);

export default ConnectedSitewideSettings;
